<template>
  <div>
    <nav class="navbar">
      <div class="container">
        <a href="#" @click.prevent="goToMain"class="navbar-brand">CampusEasyBuy</a>
        <div class="search-container">
          <input type="text" 
          class="search-input" 
          placeholder="搜索商品..."  
          v-model="searchKeyword"
          @keyup.enter="performSearch"/>
          <el-icon class="search-icon" @click="performSearch">
            <Search />
          </el-icon>
        </div>
        <el-tooltip content="高级搜索" placement="top">
          <el-button 
            type="primary" 
            class="advanced-search-btn"
            @click="navigateToFilter"
            style="margin-left: 20px;"
          >
            <!-- <el-icon class="search-icon"><Search /></el-icon> -->
            高级搜索
          </el-button>
      </el-tooltip>
        <ul class="navbar-items">
          <li v-if="isLoggedIn">
            <div class="user-profile">
              <img :src="require(`@/assets${userInfo.avatar}`)" alt="Avatar" class="user-avatar" />
              <span class="welcome-message">
                {{ welcomeMessage }}
              </span>
              <!-- 悬浮选择框 -->
              <div class="hover-menu">
                <a href="#" @click.prevent="goToAccountCenter">
                  <el-icon><Avatar /></el-icon>
                  账户中心
                </a>
                <a href="#" @click.prevent="logout">
                  <el-icon><CircleCloseFilled /></el-icon>
                  退出登录
                </a>
              </div>
            </div>
          </li>
          <li v-else>
            <a href="#" @click="showDialog">
              <el-icon><User /></el-icon> 登录
            </a>
          </li>
          <li>
               <a href="#" @click.prevent="openMessageDialog" v-if="isLoggedIn">
                 <el-icon><Message /></el-icon> 消息
               </a>
             </li>
          <li>
            <a href="#orders" @click="toOreder">
              <el-icon><Tickets /></el-icon> 订单
            </a>
          </li>
        </ul>
       <!-- 消息弹窗 -->
  <el-dialog
    v-model="messageDialogVisible"
    title="消息通知"
    width="600px"
    @opened="loadMessages"
  >
    <div v-loading="loading" class="message-container">
      <!-- 卖家消息 -->
      <div v-if="sellerMessages.length > 0">
        <h4>卖家消息</h4>
        <div 
          v-for="msg in sellerMessages"
          :key="'seller-' + msg.orderId"
          class="message-item"
          @click="handleMessageClick(msg.orderId)"
        >
          <div class="message-content">{{ msg.content }}</div>
          <div class="order-number">订单号：{{ msg.orderNumber }}</div>
        </div>
      </div>

      <!-- 买家消息 -->
      <div v-if="buyerMessages.length > 0">
        <h4>买家消息</h4>
        <div 
          v-for="msg in buyerMessages"
          :key="'buyer-' + msg.orderId"
          class="message-item"
          @click="handleMessageClick(msg.orderId)"
        >
          <div class="message-content">{{ msg.content }}</div>
          <div class="order-number">订单号：{{ msg.orderNumber }}</div>
        </div>
      </div>

      <div v-if="!sellerMessages.length && !buyerMessages.length" class="empty-tip">
        暂无新消息
      </div>
    </div>
  </el-dialog>
      </div>
    </nav>
    
    <div v-if="loginDialogVisible" class="modal-overlay" @click.self="closeDialog">
      <div class="modal">
        <span class="modal-close-button" @click="closeDialog">X</span>
        <h2>登录</h2>
        <form @submit.prevent="processLogin">
          <div class="input-group">
            <input type="text" id="username" v-model="username" placeholder="请输入用户名" required />
          </div>
          <div class="input-group">
            <input :type="showPassword ? 'text' : 'password'" id="password" v-model="password" placeholder="请输入密码" required />
            <el-icon class="toggle-password" @click="togglePasswordVisibility">
              <View v-if="!showPassword" />
              <Hide v-else />
            </el-icon>
          </div>
          <div class="forgot-password-link">
  <a href="#" @click.prevent="showForgotPasswordDialog">忘记密码？</a>
</div>
          <button type="submit" class="submit-button">登录</button>
        </form>
        <div class="login-options">
      <span class="admin-entry" @click="navigateToAdminLogin">
        管理员入口
      </span>
      <span class="register-prompt" @click="showRegisterDialog">
        没有账号？点击注册
      </span>
    </div>
      </div>
    </div>
<el-dialog
  v-model="forgotPasswordDialogVisible"
  title="重置密码"
  width="400px"
>
  <div class="forgot-password-form">
    <el-input 
      v-model="forgetPasswordData.username"
      placeholder="请输入用户名"
    />
    <el-input 
      v-model="forgetPasswordData.newPassword"
      type="password"
      placeholder="请输入新密码"
      style="margin-top: 15px;"
    />
    <div class="dialog-footer">
      <el-button @click="forgotPasswordDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="handleResetPassword">确认重置</el-button>
    </div>
  </div>
</el-dialog>
    <!-- 使用 RegisterForm 组件 -->
    <RegisterForm 
      v-if="registerDialogVisible" 
      :visible="registerDialogVisible" 
      @close="registerDialogVisible = false"
    />
  </div>
</template>

<script>
import { defineComponent } from 'vue';
import { ElIcon, ElMessage } from 'element-plus';
import { User, Tickets, View, Hide, Search, Message, Avatar, CircleCloseFilled } from '@element-plus/icons-vue';
import axios from 'axios';
import RegisterForm from './RegisterForm.vue'; // 确保路径正确

export default defineComponent({
  name: 'NavbarComponent',
  components: {
    ElIcon,
    User,
    Tickets,
    View,
    Hide,
    Search,
    Message,
    Avatar,
    CircleCloseFilled,
    RegisterForm // 注册 RegisterForm 组件
  },
  data() {
    return {
      loginDialogVisible: false,
      registerDialogVisible: false,
      username: '',
      password: '',
      showPassword: false,
      isLoggedIn: false,
      userInfo: null, // 用户信息
      dropdownVisible: false, // 下拉菜单控制
      messageDialogVisible: false,
      loading: false,
      sellerMessages: [],  // 卖家身份的消息
      buyerMessages: [] ,   // 买家身份的消息
      forgotPasswordDialogVisible: false,
    forgetPasswordData: {
      username: '',
      newPassword: ''
    }
    };
  },
  computed: {
    welcomeMessage() {
      if (!this.userInfo) return '';
      const roleName = this.userInfo.role === '01' ? '同学' : '老师';
      return `${this.userInfo.nickname} ${roleName} 欢迎！`;
    },
  },
  mounted() {
    this.getUserDetails();
  },
  methods: {
    navigateToAdminLogin() {
    const routeData = this.$router.resolve({
      path: '/admin/login'
    });
    window.open(routeData.href, '_blank');
  },

// 打开消息弹窗
openMessageDialog() {
      this.messageDialogVisible = true
    },
 // 显示忘记密码弹窗
  showForgotPasswordDialog() {
    this.forgotPasswordDialogVisible = true;
    this.loginDialogVisible = false; // 关闭登录弹窗
  },
  
  // 处理密码重置
async handleResetPassword() {
  if (!this.forgetPasswordData.username || !this.forgetPasswordData.newPassword) {
    ElMessage.error('请填写完整信息');
    return;
  }
  
  try {
    // 使用 URLSearchParams 转换参数格式
    const params = new URLSearchParams();
    params.append('username', this.forgetPasswordData.username);
    params.append('newPassword', this.forgetPasswordData.newPassword);

    const response = await axios.post(
      'http://localhost:8092/user/forgot-password',
      params,  // 直接发送 URLSearchParams 对象
      {
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded' // 关键修改
        }
      }
    );
    
    if (response.data.code === 200) {
      ElMessage.success('密码重置成功');
      this.forgotPasswordDialogVisible = false;
      this.forgetPasswordData = { username: '', newPassword: '' };
    } else {
      ElMessage.error(response.data.message || '密码重置失败');
    }
  } catch (error) {
    ElMessage.error('请求失败：' + error.message);
  }
},
    // 加载消息数据
   // 修改后的loadMessages方法
async loadMessages() {
  try {
    this.loading = true;
    const userId = this.userInfo?.userId;
    if (!userId) {
      ElMessage.error('用户信息获取失败');
      return;
    }

    // 强制类型转换处理
    const numberParser = (value) => {
      if (typeof value === 'string') {
        const num = parseInt(value, 10);
        return isNaN(num) ? 0 : num;
      }
      return Number(value) || 0;
    };

    // 获取数据（保持原请求）
    const [sellerRes, buyerRes] = await Promise.all([
      axios.get(`http://localhost:8092/order/getOrderBySellerId?sellerId=${userId}`)
        .then(res => res.data?.data || [])
        .catch(() => []),
      axios.get(`http://localhost:8092/order/getOrdersByUserId?userId=${userId}`)
        .then(res => res.data?.data || [])
        .catch(() => [])
    ]);

    // 处理卖家消息（添加类型转换）
    this.sellerMessages = (Array.isArray(sellerRes) ? sellerRes : [])
      .filter(order => numberParser(order?.afterSalesFlag) === 1)
      .map(order => ({
        orderId: numberParser(order.orderId),
        orderNumber: String(order.orderNumber || '无订单号'),
        content: `您有新的售后申请（${order.productName || '未知商品'}）待处理`
      }));

    // 处理买家消息（增强逻辑）
    this.buyerMessages = (Array.isArray(buyerRes) ? buyerRes : [])
      .filter(order => {
        const status = numberParser(order?.status);
        const flag = numberParser(order?.afterSalesFlag);
        return status === 3 || flag === 3;
      })
      .map(order => ({
        orderId: numberParser(order.orderId),
        orderNumber: String(order.orderNumber || '无订单号'),
        content: this.getBuyerMessageContent(order)
      }));

  } catch (error) {
    console.error('消息加载失败:', error);
    ElMessage.error('消息加载失败');
  } finally {
    this.loading = false;
  }
},

// 修改后的消息内容生成方法
getBuyerMessageContent(order) {
  const numberParser = (value) => {
    if (typeof value === 'string') {
      const num = parseInt(value, 10);
      return isNaN(num) ? 0 : num;
    }
    return Number(value) || 0;
  };

  const status = numberParser(order?.status);
  const flag = numberParser(order?.afterSalesFlag);
  
  // 优先显示售后拒绝状态
  if (flag === 3) {
    return `售后申请被拒：${order.rejectReason?.trim() || '未说明原因'}`;
  }
  if (status === 3) {
    return `您的订单已发货，${order.productName || '某商品'}正在运输中`;
  }
  return '未知消息类型';
},

    // 处理消息点击
    handleMessageClick(orderId) {
      console.log('点击订单ID:', orderId)
      // 实际使用时可跳转到订单详情：
      // this.$router.push(`/order/detail/${orderId}`)
    },
 
    // 搜索商品
    performSearch() {
  if (this.searchKeyword.trim()) {
    const routeData=this.$router.resolve({
      path: '/search',
      query: { keyword: this.searchKeyword }
    });
    window.open(routeData.href, '_blank');  // 打开新的标签页，并传递keyword参数
  }
},
navigateToFilter(){
  const routeData = this.$router.resolve({
    path: '/filterproduct',
  });
  window.open(routeData.href, '_blank');  // 打开新的标签页，并传递keyword参数
},
    toggleDropdown() {
      this.dropdownVisible = !this.dropdownVisible;
    },
    //前往账户中心
    goToAccountCenter() {
      // ElMessage.info('前往账户中心');
      const userId = this.userInfo ? this.userInfo.userId : null; 
      const routeData = this.$router.resolve({
      path: 'accountcenter',
      query: { userId: userId }
    });
    window.open(routeData.href, '_blank');  // 打开新的标签页，并传递userId
    },
    openAddressInNewTab() {
      console.log("点击消息")
  },
    logout() {
      this.isLoggedIn = false;
      localStorage.removeItem('token');
      ElMessage.info('已退出登录');
      this.$router.push('/');
      // location.reload();
    },
    showDialog() {
      this.loginDialogVisible = true;
    },
    closeDialog() {
      this.loginDialogVisible = false;
    },
    togglePasswordVisibility() {
      this.showPassword = !this.showPassword;
    },
    goToMain(){
      this.$router.push('/');
    },
    async processLogin() {
  try {
    const response = await axios.post('http://localhost:8092/user/login', {
      username: this.username,
      password: this.password
    });

    if (response.data.token) {
      // 登录成功处理
      const token = response.data.token;
          localStorage.setItem('token', token);
          axios.defaults.headers.common['Authorization'] = `Bearer ${token}`;

          ElMessage.success('登录成功');
          this.closeDialog();
          location.reload();
    } else if (response.data.error.includes('锁定')) {
      ElMessage.error('账户已锁定，请10分钟后再试');
    } else {
      ElMessage.error(response.data.error);
    }
  } catch (error) {
    ElMessage.error('登录请求失败');
  }
},
    showRegisterDialog() {
      this.registerDialogVisible = true;
      this.loginDialogVisible = false;
    },
    async getUserDetails() {
      const token = localStorage.getItem('token');
      if (token) {
        try {
          const response = await axios.get('http://localhost:8092/user/getUserDetails', {
            headers: {
              Authorization: `Bearer ${token}`,
            },
          });
          this.userInfo = response.data.data;
          console.log("getUserDetails userInfo:", this.userInfo)
          this.isLoggedIn = !!this.userInfo;
        } catch (error) {
          console.error('获取用户详情错误', error);
          this.isLoggedIn = false;
        }
      } else {
        this.isLoggedIn = false;
      }
    },
  },
});

</script>

<style scoped>
.navbar {
  background-color: #34495e;
  padding: 15px;
  margin-top: -60px;  /* 调整顶部的高度，使得顶部不留白*/
}

.navbar .container {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.navbar-brand {
  color: #ecf0f1;
  text-decoration: none;
  font-size: 24px;
  margin-right: auto;
}

.search-container {
  position: relative;
  flex-grow: 1;
  max-width: 400px;
}

.search-input {
  width: 100%;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 5px;
  font-size: 16px;
  box-sizing: border-box;
  padding-right: 30px;
}

.search-icon {
  position: absolute;
  right: 10px;
  top: 50%;
  transform: translateY(-50%);
  color: #34495e;
  cursor: pointer;
}

.navbar-items {
  display: flex;
  margin-left: auto;
  align-items: center;
}

.navbar-items li {
  display: inline;
  margin-left: 20px;
}

.navbar-items a {
  color: #ecf0f1;
  text-decoration: none;
  cursor: pointer;
}

.welcome-message {
  font-size: 18px;
  font-weight: bold;
  color: #ffffff;
}

.user-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  vertical-align: middle;
  cursor: pointer;
  position: relative;
}

.user-profile {
  position: relative; /* 确保 hover-menu 可以相对于这个元素定位 */
}

.hover-menu {
  display: none;
  position: absolute;
  top: 30px;
  left: 0;
  transform: translateY(10px);
  width: 150px;
  background-color: #ffffff;
  border-radius: 15px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.15);
  padding: 10px 15px;
  z-index: 100;
}

.user-profile:hover .hover-menu {
  display: block;
}

.hover-menu a {
  display: block;
  color: #333;
  padding: 5px 0;
  text-decoration: none;
}

.hover-menu a:hover {
  background-color: #f1f1f1;
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal {
  background-color: white;
  padding: 30px;
  border-radius: 8px;
  width: 400px;
  height: auto;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  position: relative;
}

.modal-close-button {
  position: absolute;
  top: 10px;
  right: 10px;
  font-size: 24px;
  cursor: pointer;
}

.input-group {
  margin-bottom: 20px;
  position: relative;
}

input[type="text"],
input[type="password"] {
  width: 100%;
  padding: 10px;
  padding-right: 40px;
  border: 1px solid #ccc;
  border-radius: 5px;
  font-size: 16px;
  box-sizing: border-box;
}

.toggle-password {
  position: absolute;
  right: 10px;
  top: 50%;
  transform: translateY(-50%);
  cursor: pointer;
  font-size: 18px;
}

.submit-button {
  background-color: #4caf50;
  color: white;
  border: none;
  padding: 10px;
  cursor: pointer;
  border-radius: 5px;
  width: 100%;
}

.submit-button:hover {
  background-color: #45a049;
}

.register-prompt {
  margin-top: 15px;
  font-size: 14px;
  color: #007BFF;
  cursor: pointer;
  text-align: center;
}
.message-container {
  max-height: 60vh;
  overflow-y: auto;
  padding: 0 20px;
}

h4 {
  color: #409EFF;
  margin: 15px 0;
  padding-bottom: 5px;
  border-bottom: 1px solid #ebeef5;
}

.message-item {
  padding: 12px;
  margin: 10px 0;
  border-radius: 4px;
  border: 1px solid #e4e7ed;
  transition: all 0.3s;
  cursor: pointer;
}

.message-item:hover {
  background: #f5f7fa;
  transform: translateX(5px);
}

.message-content {
  color: #303133;
  font-size: 14px;
}

.order-number {
  color: #909399;
  font-size: 12px;
  margin-top: 6px;
}

.empty-tip {
  text-align: center;
  color: #c0c4cc;
  padding: 30px 0;
}
.login-options {
  display: flex;
  justify-content: space-between;
  margin-top: 15px;
}

.admin-entry {
  color: #007BFF;
  cursor: pointer;
  font-size: 14px;
}

.admin-entry:hover {
  text-decoration: underline;
}

.register-prompt {
  color: #007BFF;
  cursor: pointer;
  font-size: 14px;
}
.forgot-password-link {
  text-align: right;
  margin-top: 10px;
}

.forgot-password-link a {
  color: #007BFF;
  font-size: 14px;
  text-decoration: none;
}

.forgot-password-link a:hover {
  text-decoration: underline;
}

/* 弹窗表单样式 */
.forgot-password-form {
  padding: 20px;
}

.dialog-footer {
  margin-top: 20px;
  text-align: right;
}
</style>
